<?php

namespace App\Imports;

use App\Classify;
use App\Enterprise;
use App\Merchant;
use App\MerchantMedicine;
use App\MerchantMedicineImg;
use App\MerchantMedicineXClassify;
use App\SystemMedicine;
use App\SystemMedicineImg;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Row;
use Illuminate\Support\Facades\Redis;

class ExcelToMedicine implements OnEachRow,WithHeadingRow
{
    protected $allowMerchantIdArr   = [];
    protected $storeIdCache         = [];
    protected $classifyCache        = [];
    protected $unknownRow           = [];
    protected $addFirstClassify     = [];
    protected $addSecondClassify    = [];
    protected $addMedicineNum       = [];
    protected $changeMedicineNum    = [];
    protected $i                    = 1;
    protected $errorMessage         = [];
    protected $enterprise_id        = 0;
    protected $merchantMedicineUpcTemp = [];
    protected $standardSystemMedicineNum = 0;
    protected $defaultMerchantId    = 0;
    protected $result               = [];
    protected $excel_check_id       = 0;

    public function __construct($enterprise_id,$defaultMerchantId = 0,$excel_check_id = 0)
    {
        $this->allowMerchantIdArr   = Enterprise::getEnterpriseMerchantIds($enterprise_id);
        $this->enterprise_id        = $enterprise_id;
        $this->defaultMerchantId    = $defaultMerchantId;
        $this->result['merchant_result'] = [];
        $this->excel_check_id             = $excel_check_id ?? 0;
    }


    /**
     * @param Row $row
     */
    public function onRow(Row $row)
    {
        /** 校验 */
        $this->updateDatabase($row);
        $this->i = $this->i + 1;
    }

    public function updateDatabase($row){
        /** 取值 */
        $upc                =trim($row['bar_code']) ?? '';
        $store              =trim($row['store']) ?? '';
        $first_classify     =trim($row['first_classify']) ?? '';
        $second_classify    =trim($row['second_classify']) ?? '';
        $selling_price      =trim($row['selling_price']) ?? '';
        $stock              =trim($row['stock']) ?? 0;
        $is_shop            =trim($row['is_shop']) ?? 0;
        $sort               =trim($row['sort']) ?? 0;

        if (!$upc || $upc == 'upc码' || $upc == '商品条码'){
            $this->i++;
            return null;
        }
        $this->setStatusInRedis();
        if ($store){
            //门店缓存
            $storeKey = md5($store);

            if (!isset($this->result[$storeKey])){
                $this->result[$storeKey] = [];
            }

            if (!isset($this->result[$storeKey]['add_classify']))
                $this->result[$storeKey]['add_classify'] = [];

            if (!isset($this->result[$storeKey]['notice']))
                $this->result[$storeKey]['notice'] = [];

            if (!isset($this->storeIdCache[$storeKey])){
                //查库
                $thisMerchant = Merchant::whereEnterpriseId($this->enterprise_id)
                    ->whereName($store)
                    ->first();
                if(!$thisMerchant){
                    array_push($this->result[$storeKey]['notice'],"第$this->i 行，当前企业没有该门店,本行数据被忽略，请修正后单独处理本行数据,门店名称：$store");
                    return null;
                }

                $this->storeIdCache[$storeKey] = $thisMerchant->id ?? 0;
            }
        } else {
            $storeKey = md5('default');
            if (!$this->defaultMerchantId) {
                array_push($this->result[$storeKey]['notice'],"第$this->i 行，未填写门店且未指定默认门店，本行数据被忽略，请修正后单独处理");
                return null;
            }
            if (!isset($this->result[$storeKey])){
                $this->result[$storeKey] = [];
            }

            if (!isset($this->result[$storeKey]['add_classify']))
                $this->result[$storeKey]['add_classify'] = [];

            if (!isset($this->result[$storeKey]['notice']))
                $this->result[$storeKey]['notice'] = [];

            $this->storeIdCache[$storeKey] = $this->defaultMerchantId;
        }
        if (!isset($this->changeMedicineNum[$storeKey])){
            $this->changeMedicineNum[$storeKey] = 0;
        }


        if (!isset($this->addMedicineNum[$storeKey])){
            $this->addMedicineNum[$storeKey] = 1;
        }


        if (!$this->storeIdCache[$storeKey] || !in_array($this->storeIdCache[$storeKey],$this->allowMerchantIdArr)){
            array_push($this->result[$storeKey]['notice'],"第$this->i 行，当前企业没有该门店Id,请修正后单独处理本行数据。门店Id：".$this->storeIdCache[$storeKey]);
            return null;
        }


        if ($first_classify){
            //一级分类缓存
            $classifyKey = md5($first_classify);
            if (!isset($this->classifyCache[$classifyKey])){
                //查库
                $thisClassify1 = Classify::whereEnterpriseId($this->enterprise_id)
                    ->whereMerchantId($store ? $this->storeIdCache[$storeKey] : 0)
                    ->whereType('selling')
                    ->whereName($first_classify)
                    ->first();
                if (!$thisClassify1){
                    $thisClassify1 = new Classify();
                    $thisClassify1->enterprise_id = $this->enterprise_id;
                    $thisClassify1->name          = $first_classify;
                    $thisClassify1->desc          = 'excel导入自动创建一级分类';
                    $thisClassify1->merchant_id   = $this->storeIdCache[$storeKey] ?? 0;
                    $thisClassify1->type          = 'selling';
                    $thisClassify1->save();
                    array_push($this->result[$storeKey]['add_classify'],$first_classify);
                }
                $this->classifyCache[$classifyKey] = $thisClassify1->id;
            }
        }

        if ($second_classify){
            //二级分类缓存
            $classifyKey = md5($second_classify);
            if (!isset($this->classifyCache[$classifyKey])){
                //查库
                $thisClassify2 = Classify::whereEnterpriseId($this->enterprise_id)
                    ->whereMerchantId($store ? $this->storeIdCache[$storeKey] : 0)
                    ->whereType('selling')
                    ->whereName($second_classify)
                    ->first();
                if (!$thisClassify2){
                    $thisClassify2 = new Classify();
                    $thisClassify2->enterprise_id = $this->enterprise_id;
                    $thisClassify2->name          = $second_classify;
                    $thisClassify2->desc          = 'excel导入自动创建二级分类';
                    $thisClassify2->merchant_id   = $this->storeIdCache[$storeKey] ?? 0;
                    $thisClassify2->type          = 'selling';
                    $thisClassify2->pid           = isset($thisClassify1) ? ($thisClassify1->id ?? 0): 0;
                    $thisClassify2->save();
                    array_push($this->result[$storeKey]['add_classify'],$second_classify);
                }
                $this->classifyCache[$classifyKey] = $thisClassify2->id;
            }
        }

        if ($upc){
            $exist = MerchantMedicine::whereMerchantId($this->storeIdCache[$storeKey])
                ->whereUpc($upc)
                ->first();
            if (!$exist){
                //新增
                $systemMedicine = SystemMedicine::whereStatus(1)
                    ->whereUpc($upc)
                    ->first();

                if ($systemMedicine){
                    //TODO 系统药品库商品
                    $newMerchantMedicine = new MerchantMedicine();
                    $newMerchantMedicine->upc = $upc;
                    $newMerchantMedicine->name = $systemMedicine->name ?? '';
                    $newMerchantMedicine->merchant_id = $this->storeIdCache[$storeKey];
                    $newMerchantMedicine->approval_number = $systemMedicine->approval_number ?? '';
                    $newMerchantMedicine->specification = $systemMedicine->specification ?? '';
                    $newMerchantMedicine->selling_price = $selling_price ? $selling_price : 0;
                    $newMerchantMedicine->stock = $stock ? $stock : 0;
                    $newMerchantMedicine->manufacturer = $systemMedicine->manufacturer ?? '';
                    $newMerchantMedicine->manufacturer_address = $systemMedicine->manufacturer_address ?? '';
                    $newMerchantMedicine->manufacturer_contact = $systemMedicine->manufacturer_contact ?? '';
                    $newMerchantMedicine->electronic_regulatory_code = $systemMedicine->electronic_regulatory_code ?? '';
                    $newMerchantMedicine->usage_and_dosage = $systemMedicine->usage_and_dosage ?? '';
                    $newMerchantMedicine->indications = $systemMedicine->indications ?? '';
                    $newMerchantMedicine->adapt_to_the_crowd = $systemMedicine->adapt_to_the_crowd ?? '';
                    $newMerchantMedicine->component = $systemMedicine->component ?? '';
                    $newMerchantMedicine->adverse_reactions = $systemMedicine->adverse_reactions ?? '';
                    $newMerchantMedicine->contraindications = $systemMedicine->contraindications ?? '';
                    $newMerchantMedicine->precautions = $systemMedicine->precautions ?? '';
                    $newMerchantMedicine->interaction = $systemMedicine->interaction ?? '';
                    $newMerchantMedicine->medication_for_children = $systemMedicine->medication_for_children ?? '';
                    $newMerchantMedicine->medication_for_pregnancy_x_lactation = $systemMedicine->medication_for_pregnancy_x_lactation ?? '';
                    $newMerchantMedicine->medication_for_aged = $systemMedicine->medication_for_aged ?? '';
                    $newMerchantMedicine->properties = $systemMedicine->properties ?? '';
                    $newMerchantMedicine->packing = $systemMedicine->packing ?? '';
                    $newMerchantMedicine->dosage_form = $systemMedicine->dosage_form ?? '';
                    $newMerchantMedicine->storage = $systemMedicine->storage ?? '';
                    $newMerchantMedicine->pharmacological_action = $systemMedicine->pharmacological_action ?? '';
                    $newMerchantMedicine->expiry_date = $systemMedicine->expiry_date ?? '';
                    $newMerchantMedicine->detail = $systemMedicine->detail ?? '';
                    $newMerchantMedicine->is_shop = $is_shop ? 1 : 0;
                    $newMerchantMedicine->sort = $sort ? $sort : 0;
                    $newMerchantMedicine->drug_type = $systemMedicine->drug_type;
                    $newMerchantMedicine->save();
                    if ($this->classifyCache[md5($first_classify)] != '') {
                        $newMerchantMedicineClassify = new MerchantMedicineXClassify();
                        $newMerchantMedicineClassify->merchant_medicine_id  = $newMerchantMedicine->id;
                        $newMerchantMedicineClassify->classify_id           = $this->classifyCache[md5($first_classify)];
                        $newMerchantMedicineClassify->save();
                    }
                    if ($this->classifyCache[md5($second_classify)] != ''){
                        $newMerchantMedicineClassifyTwo = new MerchantMedicineXClassify();
                        $newMerchantMedicineClassifyTwo->merchant_medicine_id = $newMerchantMedicine->id;
                        $newMerchantMedicineClassifyTwo->classify_id = $this->classifyCache[md5($second_classify)];
                        $newMerchantMedicineClassifyTwo->save();
                    }
                    $systemMedicineImgList = SystemMedicineImg::whereSystemMedicineId($systemMedicine->id)->get();
                    if (count($systemMedicineImgList) > 0) {
                        foreach ($systemMedicineImgList as $item){
                            MerchantMedicineImg::firstOrCreate(
                                ['merchant_medicine_id'=>$newMerchantMedicine->id, 'img_id'=>$item->img_id,],
                                ['sort'=>$item->sort]);
                        }
                    }
//                    if (!isset($this->addMedicineNum[$storeKey])){
//                        $this->addMedicineNum[$storeKey] = 1;
//                    } else {
                        $this->addMedicineNum[$storeKey]++;
//                    }

                } else {
                    //TODO　非标商品
                    return null;
                }

            } else {
                //修改
                $exist->selling_price = $selling_price ? $selling_price : 0;
                $exist->stock = $stock ? $stock : 0;
                $exist->is_shop = $is_shop ? $is_shop : 0;
                $exist->sort = $sort ? $sort : 0;
                $exist->save();
//                if (!isset($this->changeMedicineNum[$storeKey])){
//                    $this->changeMedicineNum[$storeKey] = 0;
//                } else {
                    $this->changeMedicineNum[$storeKey]++;
//                }
            }
            //TODO　非标处理
        }
    }

    public function getResult(){
        $this->result['merchant_result']=[];
        if (count($this->storeIdCache) > 0){
            foreach ($this->storeIdCache as $nameMD5=>$merchantId){
                $merchant_name      = Merchant::getMerchantName($merchantId);
                $add_classify       = $this->result[$nameMD5]['add_classify'];
                $add_medicineNum    = $this->addMedicineNum[$nameMD5];
                $change_medicineNum = $this->changeMedicineNum[$nameMD5];
                $temp           = [
                    'merchant_name'     =>$merchant_name,
                    'add_classify'      =>$add_classify,
                    'add_medicineNum'   =>$add_medicineNum,
                    'change_medicineNum'=>$change_medicineNum
                ];
                array_push($this->result['merchant_result'],$temp);
            }

        }

        return $this->result;
    }

    public function getErrorMessage(){
        return $this->errorMessage;
    }

    protected function setStatusInRedis(){
        $status = Redis::get('job.xlsx.st'.$this->excel_check_id);
        $status = json_decode($status);
        if (isset($status->now) && $status->now >= 0){
            $status->now = $status->now + 1;
        } else {
            $status->now = 0;
        }
        Redis::set('job.xlsx.st'.$this->excel_check_id,json_encode($status),'EX','1800');
    }


}
